//
//  BabyViewController.m
//  MM
//
//  Created by 郑渊文 on 5/19/15.
//  Copyright (c) 2015 王晨辉. All rights reserved.
//

#import "BabyViewController.h"
#import "CommonMacro.h"
#import "MyFamilyViewController.h"
#import "AddBabyViewController.h"
#import "BabyManager.h"
#define kDeleteRecordAlertT 10001

@interface BabyViewController ()<UITableViewDataSource,UITableViewDelegate>

{
    UIButton *addbabyBtn;
    UIButton *backBtn;
     NSIndexPath             *dexPath;
}


@property(nonatomic,copy)UITableView *myTable;
@property(nonatomic,copy)NSString *babydayStr;

@end

@implementation BabyViewController


//- (NSMutableArray *)nameArray
//{
//    if (nil == _nameArray)
//    {
//        _nameArray = [NSMutableArray array];
//    }
//    return _nameArray;
//}
//
//- (NSMutableArray *)timeArray
//{
//    if (nil == _timeArray)
//    {
//        _timeArray = [NSMutableArray array];
//    }
//    return _timeArray;
//}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self initSubViews];
    self.view.backgroundColor = [UIColor whiteColor];
    _nameArray = [NSMutableArray array];
    _timeArray = [NSMutableArray array];
    _babyIdArray = [NSMutableArray array];
    _gender = [NSMutableArray array];
    _dayArray = [NSMutableArray array];

//    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
//    NSString *ID = [user objectForKey:@"ID"];
//
//    NSDictionary *param = @{@"userId": ID};
//    [UserDAL getBabysParams:param withBlock:^(NSDictionary *data, NSError *error) {
//        if (data) {
//            ////NSLog(@"=========================%@",data);
//            
//            NSArray *myArray =data[@"dataList"];
//            for (NSDictionary *myDic in myArray) {
//                [_nameArray addObject:myDic[@"babyName"]];
//                [_timeArray addObject:myDic[@"babyAge"]];
//                [_babyIdArray addObject:myDic[@"ID"]];
//                [_gender addObject:myDic[@"gender"]];
//
//            }
//            [_myTable reloadData];
////            [self ShowProgressHUDwithMessage:data[@"msg"]];
//            
//        }
//        else
//        {
//            
//        }
//    }];
    //    _nameArray = @[@"郑天才",@"逗比",@"哈哈哈哈"];
    //    _timeArray = @[@"10年8天",@"10年7天",@"10年6天"];
    // Do any additional setup after loading the view.
}

-(void)viewWillAppear:(BOOL)animated
{
    
    [super viewWillAppear:animated];
    [self ShowProgressHUDwithMessage:@"宝宝正在路上"];

    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    NSString *ID = [user objectForKey:@"ID"];
    
    [_nameArray removeAllObjects];
    [_timeArray removeAllObjects];
    [_babyIdArray removeAllObjects];
    [_gender removeAllObjects];
    [_dayArray removeAllObjects];


    NSDictionary *param = @{@"userId": ID};
    [UserDAL getBabysParams:param withBlock:^(NSDictionary *data, NSError *error) {
        if (data) {
//            //NSLog(@"=========================%@",data);

            NSArray *myArray =data[@"dataList"];
            for (NSDictionary *myDic in myArray) {
                [_nameArray addObject:myDic[@"babyName"]];
                [_timeArray addObject:myDic[@"babyAge"]];
                [_babyIdArray addObject:myDic[@"ID"]];
                [_gender addObject:myDic[@"gender"]];
                [_dayArray addObject:myDic[@"babyDay"]];


                
                
            }
            [_myTable reloadData];
            //            [self ShowProgressHUDwithMessage:data[@"msg"]];
            
        }
        else
        {
            
        }
    }];

}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)initSubViews
{
    self.navigationItem.title = @"宝宝";
    [self.navigationController.navigationBar setTranslucent:NO];//设置navigationbar的半透明
    [self.navigationController.navigationBar setBarTintColor:[GetFileModel colorWithHexString:@"#34bd81" alpha:1]];
    [self.navigationController.navigationBar setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIColor whiteColor],NSForegroundColorAttributeName,nil]];

    self.view.backgroundColor = [UIColor clearColor];
    
    _myTable = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
    [self.view addSubview:_myTable];
    _myTable.delegate = self;
    _myTable.dataSource = self;
//    _myTable.separatorStyle = UITableViewCellSeparatorStyleNone;

    
//        backBtn = [[UIButton alloc]initWithFrame:CGRectMake(SCREEN_WIDTH - 50, 10,80, 30)];
//        [backBtn setTitle:@"返回" forState:UIControlStateNormal];
//        [backBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
//        [backBtn addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
//        backBtn.backgroundColor = UIColorWithRGBA(219, 99, 101, 1);
//        //    [RegistBtn setBackgroundColor:[UIColor clearColor]];
//        [self.navigationController.navigationBar addSubview:backBtn];
    
    UIButton *addBaby = [[UIButton alloc]initWithFrame:CGRectMake(SCREEN_WIDTH - 60, 10,40, 30)];
    [addBaby addTarget:self action:@selector(addBabyToFamily) forControlEvents:UIControlEventTouchUpInside];
    [addBaby setTitle:@"添加" forState:UIControlStateNormal];
//    addBaby.backgroundColor = UIColorWithRGBA(219, 99, 101, 1);
    addBaby.layer.cornerRadius = 5;
    [self.navigationController.navigationBar addSubview:addBaby];
    
    
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    [button setBackgroundImage:[UIImage imageNamed:@"_0000_返回.png"]
                      forState:UIControlStateNormal];
    [button addTarget:self action:@selector(backs)
     forControlEvents:UIControlEventTouchUpInside];
    button.frame = CGRectMake(0, 0, 20, 15);
    
    
    UIBarButtonItem *menuButton = [[UIBarButtonItem alloc] initWithCustomView:button];
    
    self.navigationItem.leftBarButtonItem = menuButton;

    
    
    
//    UILongPressGestureRecognizer *longPressGR = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPressToDo:)];
//    longPressGR.minimumPressDuration = 1.0;
//    [_myTable addGestureRecognizer:longPressGR];
    

    
    
}

-(void)backs{
    
    [self dismissViewControllerAnimated:YES completion:nil];
    
}

#pragma mark--- tableViewDelegate 每个区的行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _nameArray.count;
}
#pragma mark--- tableViewDelegate 区尾的高度

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0;
}
#pragma mark--- tableViewDelegate cell

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
//    static NSString *NOTIFY = @"cell";
//    UITableViewCell *cell = (UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:NOTIFY];
    NSString *CellIdentifier = [NSString stringWithFormat:@"Cell%ld%ld", (long)[indexPath section], (long)[indexPath row]];//以indexPath来唯一确定cell
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell==nil) {
        cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
        
        UIView * view = [[UIView alloc]initWithFrame:CGRectMake(0, _myTable.rowHeight-1, SCREEN_WIDTH, 1)];
        view.backgroundColor = UIColorWithRGBA(229, 229, 231, 1);
        [cell addSubview:view];
        
        _myTable.tableFooterView = [[UIView alloc]init];

        
        UILongPressGestureRecognizer * longPressGesture = [[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(cellLongPress:)];
        [cell addGestureRecognizer:longPressGesture];
        longPressGesture.minimumPressDuration = 1.0;
        
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        UILabel *nameLable = [[UILabel alloc]initWithFrame:CGRectMake(20, 10, 80, 20)];
        nameLable.text= _nameArray[indexPath.row];
        UILabel *timeLable = [[UILabel alloc]initWithFrame:CGRectMake(140, 10, 100, 20)];
        
        NSString *babyAge = [NSString stringWithFormat:@"%@",_dayArray[indexPath.row]];
        NSString * Year = [NSString stringWithFormat:@"%d",[babyAge intValue]/365];
        NSString * day2 = [NSString stringWithFormat:@"%d",[babyAge intValue]-[Year intValue]*365];
        NSString * April = [NSString stringWithFormat:@"%d",[day2 intValue]/30];
        //                //NSLog(@"%@岁%@月%@",day1,day3,day2);
        
        if ([April isEqualToString:@"0"]) {
            if ([Year isEqualToString:@"0"]&&[April isEqualToString:@"0"]){
                
                _babydayStr = [NSString stringWithFormat:@"1个月"];
                
                
            }else{
                _babydayStr = [NSString stringWithFormat:@"%@岁",Year];

            }
            
            
        }else if ([Year isEqualToString:@"0"]){
            
            if ([Year isEqualToString:@"0"]&&[April isEqualToString:@"0"]){
                
                _babydayStr = [NSString stringWithFormat:@"1个月"];
                
                
            }else{
                _babydayStr = [NSString stringWithFormat:@"%@个月",April];

                
            }
            
            
        }else{
            
            _babydayStr = [NSString stringWithFormat:@"%@岁%@个月",Year,April];
            
            
        }
        timeLable.text =[NSString stringWithFormat:@"%@",_babydayStr];
        timeLable.adjustsFontSizeToFitWidth = YES;
        timeLable.textColor = [UIColor lightGrayColor];
        [cell addSubview:nameLable];
        [cell addSubview:timeLable];

        

        
        
    }
    
//    else{
//        for (UIView *subView in cell.subviews)
//        {
//            [subView removeFromSuperview];
//        }
//    }
    
    

    return cell;
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex

{
    
    
    if (buttonIndex == 0) {
        
//        [self dismissViewControllerAnimated:YES completion:nil];
        //NSLog(@"1111111.%ld",(long)dexPath.row);
        
        
        
        
    }else if(buttonIndex == 1){
        
        
        //NSLog(@"22222.%ld",(long)dexPath.row);
        
        NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
        NSString *ID = [user objectForKey:@"ID"];
        
        NSString *babyId = [NSString stringWithFormat:@"%@",_babyIdArray[dexPath.row]];
        NSString *oldbabyId = [NSString stringWithFormat:@"%@",[BabyManager shareInstance].babyId];
        
        if ([babyId isEqualToString: oldbabyId]) {
            
            //NSLog(@"111");
            NSString *babyName = @"";
            NSUserDefaults *user1 = [NSUserDefaults standardUserDefaults];
            [user1 setObject:babyName forKey:@"babyName"];
            
            NSString *babyAge = @"";
            NSUserDefaults *user2 = [NSUserDefaults standardUserDefaults];
            [user2 setObject:babyAge forKey:@"babyAge"];
            
            
        }else{
            
            
            //NSLog(@"222");
            
            
        }
        
        
        NSDictionary *param = @{@"userId": ID,@"babyId":babyId};
        [UserDAL getDeletebabyParams: param withBlock:^(NSDictionary *data, NSError *error) {
            if (data) {
                ////NSLog(@"=========================%@",data);
                
                NSArray *dataList = data[@"dataList"];
                if (dataList.count == 0) {
                    //NSLog(@"删完了");
                    
                    
                    
                    NSString *nasty = @"1";
                    NSUserDefaults *user1 = [NSUserDefaults standardUserDefaults];
                    [user1 setObject:nasty forKey:@"nasty"];
                    
                    NSString *babyName = @"";
                    NSUserDefaults *user3 = [NSUserDefaults standardUserDefaults];
                    [user3 setObject:babyName forKey:@"babyName"];
                    
                    NSString *babyAge = @"";
                    NSUserDefaults *user2 = [NSUserDefaults standardUserDefaults];
                    [user2 setObject:babyAge forKey:@"babyAge"];
                    
                    
                    
                    [BabyManager shareInstance].babyId = nil;
                    
                } else {
                    //NSLog(@"还有我");
                    
                    
                    NSString *nasty = @"0";
                    NSUserDefaults *user1 = [NSUserDefaults standardUserDefaults];
                    [user1 setObject:nasty forKey:@"nasty"];
                    
                    
                    
                }
                
                [self ShowProgressHUDwithMessage:data[@"msg"]];
                
            }
            else
            {
                
            }
        }];
        
        
        
        
        [_nameArray removeObjectAtIndex:dexPath.row];
        [_timeArray removeObjectAtIndex:dexPath.row];
        [_babyIdArray removeObjectAtIndex:dexPath.row];
        [_myTable reloadData];

        
        
    }else if(buttonIndex == 2){
        
        
        //NSLog(@"33333.%ld",(long)dexPath.row);
        [BabyManager shareInstance].babyId = _babyIdArray[dexPath.row];
        [BabyManager shareInstance].homeName = _nameArray[dexPath.row];
        
        NSString *babyName = [NSString stringWithFormat:@"%@",_nameArray[dexPath.row]];
        NSUserDefaults *user1 = [NSUserDefaults standardUserDefaults];
        [user1 setObject:babyName forKey:@"babyName"];
        
        
        NSString *babyAge = [NSString stringWithFormat:@"%@",_dayArray[dexPath.row]];
        NSString * Year = [NSString stringWithFormat:@"%d",[babyAge intValue]/365];
        NSString * day2 = [NSString stringWithFormat:@"%d",[babyAge intValue]-[Year intValue]*365];
        NSString * April = [NSString stringWithFormat:@"%d",[day2 intValue]/30];
        //                //NSLog(@"%@岁%@月%@",day1,day3,day2);
        
        if ([April isEqualToString:@"0"]) {
            if ([Year isEqualToString:@"0"]&&[April isEqualToString:@"0"]){
                
                _babydayStr = [NSString stringWithFormat:@"1个月"];
                
                
            }else{
                _babydayStr = [NSString stringWithFormat:@"%@岁",Year];
                
            }
            
            
        }else if ([Year isEqualToString:@"0"]){
            
            if ([Year isEqualToString:@"0"]&&[April isEqualToString:@"0"]){
                
                _babydayStr = [NSString stringWithFormat:@"1个月"];
                
                
            }else{
                _babydayStr = [NSString stringWithFormat:@"%@个月",April];
                
                
            }
            
            
        }else{
            
            _babydayStr = [NSString stringWithFormat:@"%@岁%@个月",Year,April];
            
            
        }
        
        
        NSUserDefaults *user2 = [NSUserDefaults standardUserDefaults];
        [user2 setObject:_babydayStr forKey:@"babyAge"];
        
        
        
        NSString *babyid = [NSString stringWithFormat:@"%@",_babyIdArray[dexPath.row]];
        NSUserDefaults *user3 = [NSUserDefaults standardUserDefaults];
        [user3 setObject:babyid forKey:@"babyAid"];
        
        
        [self dismissViewControllerAnimated:YES completion:^{
        }];
        

        
    }else{
        
        
        NSString *babyId = [NSString stringWithFormat:@"%@",_babyIdArray[dexPath.row]];
        AddBabyViewController *addBabyVC = [[AddBabyViewController alloc]init];
        addBabyVC.myBabyId = babyId;
        ////NSLog(@"===============================%@",addBabyVC.myBabyId);
        addBabyVC.mybabyName = [NSString stringWithFormat:@"%@",_nameArray[dexPath.row]] ;
        ////NSLog(@"===============================%@",addBabyVC.mybabyName);
        addBabyVC.gender = _gender[dexPath.row];
        ////NSLog(@"%@",_gender[dexPath.row]);
        UINavigationController * nav = [[UINavigationController alloc]initWithRootViewController:addBabyVC];
        [self  presentViewController:nav animated:YES completion:nil];
        
        

        
        
    }
    
    
}


#pragma mark--- tableViewDelegat 点击方法

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    dexPath = indexPath;

    
    UIAlertView * alert = [[UIAlertView alloc]initWithTitle:@"请选择" message:nil delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"删除",@"切换",@"修改", nil];
    [alert show];
    
    
    
    
    
}



//3.删除操作：

#pragma mark -
#pragma mark UIAlertViewDelegate
//- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
//{
//    if (alertView.tag == kDeleteRecordAlertT)
//    {
//        if (buttonIndex == 0)
//        {
//        }
//        else if (buttonIndex == 1)
//        {
//            [self delete:[_nameArray objectAtIndex:_indexPath.row]];
//            [_nameArray removeObjectAtIndex:_indexPath.row];
//            [_myTable deleteRowsAtIndexPaths:[NSArray arrayWithObject:_indexPath] withRowAnimation:UITableViewRowAnimationFade];
//        }
//    }
//    
//}


- (void)cellLongPress:(UIGestureRecognizer *)recognizer{
    if (recognizer.state == UIGestureRecognizerStateBegan) {
        CGPoint location = [recognizer locationInView:self.myTable];
        dexPath = [self.myTable indexPathForRowAtPoint:location];
        ////NSLog(@"%d",dexPath.row);
        UITableViewCell *cell = (UITableViewCell *)recognizer.view;
//这里把cell做为第一响应(cell默认是无法成为responder,需要重写canBecomeFirstResponder方法)
        [cell becomeFirstResponder];
        
        UIMenuItem *itDelete = [[UIMenuItem alloc] initWithTitle:@"删除" action:@selector(handleDelegateCell:)];
        UIMenuItem *itChange = [[UIMenuItem alloc] initWithTitle:@"修改" action:@selector(handleChangeCell:)];
        UIMenuController *menu = [UIMenuController sharedMenuController];
        [menu setMenuItems:[NSArray arrayWithObjects:itDelete, itChange,  nil]];
        [menu setTargetRect:cell.frame inView:self.myTable];
        [menu setMenuVisible:YES animated:YES];

    }
}

- (BOOL)canBecomeFirstResponder{
    return YES;
}

- (void)handleDelegateCell:(id)sender{//删除cell
    ////NSLog(@"点击了删除");

    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    NSString *ID = [user objectForKey:@"ID"];

        NSString *babyId = [NSString stringWithFormat:@"%@",_babyIdArray[dexPath.row]];
        NSString *oldbabyId = [NSString stringWithFormat:@"%@",[BabyManager shareInstance].babyId];

    if ([babyId isEqualToString: oldbabyId]) {
        
        //NSLog(@"111");
        NSString *babyName = @"";
        NSUserDefaults *user1 = [NSUserDefaults standardUserDefaults];
        [user1 setObject:babyName forKey:@"babyName"];
        
        NSString *babyAge = @"";
        NSUserDefaults *user2 = [NSUserDefaults standardUserDefaults];
        [user2 setObject:babyAge forKey:@"babyAge"];

        
    }else{
        
        
        //NSLog(@"222");
        
    }
    
    
        NSDictionary *param = @{@"userId": ID,@"babyId":babyId};
        [UserDAL getDeletebabyParams: param withBlock:^(NSDictionary *data, NSError *error) {
            if (data) {
                ////NSLog(@"=========================%@",data);
                
                NSArray *dataList = data[@"dataList"];
                if (dataList.count == 0) {
                    //NSLog(@"删完了");

                    
                    
                    NSString *nasty = @"1";
                    NSUserDefaults *user1 = [NSUserDefaults standardUserDefaults];
                    [user1 setObject:nasty forKey:@"nasty"];
                    
                    NSString *babyName = @"";
                    NSUserDefaults *user3 = [NSUserDefaults standardUserDefaults];
                    [user3 setObject:babyName forKey:@"babyName"];
                    
                    NSString *babyAge = @"";
                    NSUserDefaults *user2 = [NSUserDefaults standardUserDefaults];
                    [user2 setObject:babyAge forKey:@"babyAge"];

                    

                    [BabyManager shareInstance].babyId = nil;

                } else {
                    //NSLog(@"还有我");
                    

                    NSString *nasty = @"0";
                    NSUserDefaults *user1 = [NSUserDefaults standardUserDefaults];
                    [user1 setObject:nasty forKey:@"nasty"];

                    

                }
                
                [self ShowProgressHUDwithMessage:data[@"msg"]];
                
            }
            else
            {
                
            }
        }];
    
    
    

    [_nameArray removeObjectAtIndex:dexPath.row];
    [_timeArray removeObjectAtIndex:dexPath.row];
    [_babyIdArray removeObjectAtIndex:dexPath.row];
    [_myTable reloadData];
//        [self.myTable deleteRowsAtIndexPaths:[NSArray arrayWithObjects:dexPath, nil] withRowAnimation:UITableViewRowAnimationTop];
    
}

- (void)handleChangeCell:(id)sender{//修改cell
    ////NSLog(@"点击了修改");
    ////NSLog(@"%@",_gender[dexPath.row]);

    
    NSString *babyId = [NSString stringWithFormat:@"%@",_babyIdArray[dexPath.row]];
    AddBabyViewController *addBabyVC = [[AddBabyViewController alloc]init];
    addBabyVC.myBabyId = babyId;
    ////NSLog(@"===============================%@",addBabyVC.myBabyId);
    addBabyVC.mybabyName = [NSString stringWithFormat:@"%@",_nameArray[dexPath.row]] ;
    ////NSLog(@"===============================%@",addBabyVC.mybabyName);
    addBabyVC.gender = _gender[dexPath.row];
    ////NSLog(@"%@",_gender[dexPath.row]);
    UINavigationController * nav = [[UINavigationController alloc]initWithRootViewController:addBabyVC];
    [self  presentViewController:nav animated:YES completion:nil];
//
}


-(void)addBabyToFamily
{
    AddBabyViewController *addBabyVC = [[AddBabyViewController alloc]init];
    addBabyVC.myBabyId = @"0";
    addBabyVC.gender = @"3";
    addBabyVC.city = @"1";

        UINavigationController * nav = [[UINavigationController alloc]initWithRootViewController:addBabyVC];
        [self  presentViewController:nav animated:YES completion:nil];
//    [self.navigationController pushViewController:addBabyVC animated:YES];
    
}

-(void)back
{
    [self popoverPresentationController];
}

- (void)ShowProgressHUDwithMessage:(NSString *)msg
{
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:[UIApplication sharedApplication].keyWindow animated:YES];
    hud.mode = MBProgressHUDModeText;
    hud.labelText = msg;
    hud.dimBackground = NO;
    hud.removeFromSuperViewOnHide = YES;
    [hud hide:YES afterDelay:1];
}
/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
